package com.shuhe.handler;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.TypeUtils;
import com.shuhe.common.ReflectUtil;
import com.shuhe.domain.serviceTest.YzRequestBody;
import com.shuhe.domain.serviceTest.YzResponseBody;
import com.shuhe.domain.serviceTest.YzResponseBodyData;
import com.shuhe.domain.serviceTest.YzResponseBodyDataResult;
import com.shuhe.gauss.SearchGauss;
import com.shuhe.metastore.MetaMysql;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.*;

import static com.shuhe.common.CommonFunction.*;

public class ServiceTestHandler extends HttpServlet {
    private static Logger logger = Logger.getLogger(ServiceTestHandler.class);

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {

            /*

            String result = "{\n" +
                    "  \"result\": \"200\"\n" +
                    "}";
            resp.getWriter().write(result);

             */


            req.setCharacterEncoding("UTF-8");
            resp.setCharacterEncoding("UTF-8");
            String tab_name = req.getParameter("tab_name");
            String appId = req.getHeader("yyzyml_id");
            resp.setContentType("text/html;charset=utf-8");
            String ifOrder = req.getHeader("ifOrder");
            if (appId == null) {
                resp.getWriter().write("appId为必传参数");
                return;
            }
            String bodyStr = readAsChars(req);
            //json相关
            JSONObject bodyJson = JSONObject.parseObject(bodyStr);
            YzRequestBody fhReq = JSONObject.toJavaObject(bodyJson, YzRequestBody.class);

            fhReq.setTab_name(tab_name);
            fhReq.setAppId(appId);


            String fhResp = execSql(fhReq, ifOrder); //主方法
            resp.getWriter().write(fhResp);


        } catch (Exception ex) {
            ex.printStackTrace();
            resp.getWriter().write(returnFail(ex.getMessage()));
        }
    }

    public static String execSql(YzRequestBody fhReq, String ifOrder) {

        //返回行数约定
        if (fhReq.getMaxReturnNum().trim().length() == 0) {
            fhReq.setMaxReturnNum(" 10 ");
        }
        //如果未传返回行数，限定10行
        int maxNum = Integer.valueOf(fhReq.getMaxReturnNum());
        if (maxNum > 2000) {
            fhReq.setMaxReturnNum("2000");
        }
        //如果超过2000行，返回2000行

        //开始时间
        long beginTime = Calendar.getInstance().getTimeInMillis();
        // 执行ES查询
        SearchGauss gauss = new SearchGauss();
        if (fhReq.getOrderParafs() == null) {
            fhReq.setOrderParafs("");
        }
        String orderStr = fhReq.getOrderParafs().toString();
        orderStr = orderStr.replaceAll("\"", "")
                .replaceAll(":", " ")
                .replaceAll("\\{", "")
                .replaceAll("}", "");
        if (orderStr.length() < 3) {
            orderStr = "";
        }
        String fieldStr = "no found";
        try {
            MetaMysql mysql = new MetaMysql();
            Connection conn = MetaMysql.connect();
            if (conn.isClosed()) {
                conn = MetaMysql.connect();
            }
            //列值确定
            ArrayList<String> fieldStrInput = new ArrayList<>();
            for (int i = 0; i < fhReq.getParafs().size(); i++) {
                fieldStrInput.add(fhReq.getParafs().get(i));
            }
            System.out.println(fieldStrInput);
            fieldStr = "";
            for (int i = 0; i < fieldStrInput.size(); i++) {
                String sql = "SELECT\n" +
                        "\te.column_name\n" +
                        "FROM\n" +
                        "\tklj_sjkf_fwsq_mx a\n" +
                        "JOIN klj_sjkf_fwzyml c ON a.fwzyml_id = c.id\n" +
                        "JOIN klj_sjkf_fwsq b ON a.id = b.id\n" +
                        "AND b.yyzyml_id = '" + fhReq.getAppId() + "'\n" +
                        "JOIN klj_sjzc_tab d ON c.table_name = d.table_name\n" +
                        "JOIN klj_sjzc_col e ON d.m_table_id = e.table_id\n" +
                        "where c.table_name='" + fhReq.getTab_name().toLowerCase() + "'";
                ResultSet rs = mysql.querySql(conn, sql);
                while (rs.next()) {
                    if (fieldStrInput.get(i).equals(rs.getString("column_name"))) {
                        fieldStr = fieldStr.concat(rs.getString("column_name")).concat(",");
                    }
                }
            }
            fieldStr = fieldStr.substring(0, fieldStr.length() - 1);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        /////很奇怪
        if (fieldStr.equals("no found")) {
            return "appId为必传参数";
        }
        ArrayList<String> gaussResp = gauss.callSearch(fhReq.getTab_name(), fhReq.getMaxReturnNum(),
                fhReq.getCondition(), orderStr, fieldStr);
        long endTime = Calendar.getInstance().getTimeInMillis();
        String qTime = String.valueOf(endTime - beginTime);
        //log.warn("qtime:" + qTime);
        YzResponseBody resp = new YzResponseBody();
        resp.setMessageSequence(fhReq.getMessageSequence());
        resp.setMsg("成功");
        resp.setStatus("200");
        resp.setQtime(qTime);
        YzResponseBodyData data = new YzResponseBodyData();
        if (!fieldStr.equals("*")) {
            //如果有列限制
            String[] strs = fieldStr.split(",");
            ArrayList als = new ArrayList(Arrays.asList(strs));
            fhReq.setParafs(als);
        }
        data.setTotalRows(String.valueOf(gaussResp.size()));
        ArrayList<Object> results = new ArrayList();
        YzResponseBodyDataResult result = new YzResponseBodyDataResult();
        for (int i = 0; i < gaussResp.size(); i++) {
            Map<String, Object> addProperties = new HashMap();
            for (int j = 0; j < fhReq.getParafs().size(); j++) {
                String fieldName = fhReq.getParafs().get(j);
                String[] temp = gaussResp.get(i).split(",");
                String valueStr = temp[j];
                addProperties.put(fieldName, valueStr);
            }
            Object obj = ReflectUtil.getTarget(result, addProperties);
            results.add(obj);
        }
        data.setResults(results);
        resp.setData(data);
        TypeUtils.compatibleWithJavaBean = true;  //8.2 JQH
        String respJson = JSONObject.toJSONString(resp);
        return respJson.toString();
    }


}
